﻿using System;
using System.Collections.Generic;
using System.Linq;
using Flux.Data.Layers;
using Flux.Data.Tilesets;

namespace Flux.Data.Maps
{
	public class Map
	{
		private readonly List<ILayer> _layers = new List<ILayer>();
		private readonly List<string> _layerNames = new List<string>();
		private readonly List<Tileset> _tilesets = new List<Tileset>(); 

		public Guid Id { get; set; }
		public string Name { get; set; }
		public int Width { get; set; }
		public int Height { get; set; }
		public int TileWidth { get; set; }
		public int TileHeight { get; set; }

		public List<Tileset> Tilesets
		{
			get { return _tilesets; }
		}

		public List<ILayer> Layers
		{
			get { return _layers; }
		}

		public Map()
		{
			Id = Guid.NewGuid();
		}

		public void AddLayer(string alias, ILayer layer)
		{
			layer.Width = Width;
			layer.Height = Height;

			if (layer is TileLayer)
			{
				var tileLayer = ((TileLayer) layer);
				tileLayer.TileWidth = TileWidth;
				tileLayer.TileHeight = TileHeight;
			}

			_layerNames.Add(alias);
			_layers.Add(layer);
		}

		public void RemoveLayer(string alias)
		{
			var index = _layerNames.IndexOf(alias);
			_layers.RemoveAt(index);
			_layerNames.RemoveAt(index);
		}

		public void RemoveLayer(ILayer layer)
		{
			var index = _layers.IndexOf(layer);
			_layers.RemoveAt(index);
			_layerNames.RemoveAt(index);
		}

		public void Clear()
		{
			_layerNames.Clear();
			_layers.Clear();
		}

		public Tileset GetTileset(Guid id)
		{
			return Tilesets.FirstOrDefault(tileset => tileset.Id == id);
		}
	}
}